package com.proposition.web.exam;

import com.baomidou.mybatisplus.plugins.Page;
import com.proposition.commons.exam.bean.ExamSearchItem;
import com.proposition.commons.exam.exception.ExamException;
import com.proposition.commons.exam.result.Result;
import com.proposition.commons.exam.result.ResultEnum;
import com.proposition.commons.exam.result.ResultUtil;
import com.proposition.commons.exam.util.ExamManageUtil;
import com.proposition.commons.exam.util.ExamUtil;
import com.proposition.commons.exam.vo.ExamVO;
import com.proposition.commons.model.*;
import com.proposition.exam.service.IServiceExamManage;
import com.proposition.paper.service.PaperService;
import com.proposition.support.annotation.LogAnnotation;
import com.proposition.support.security.CurrentUser;
import freemarker.template.TemplateException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 陈玉林
 * @modifiedBy:
 * @date: Create In 14:56 2017/12/5
 * @description:
 */
@Controller
@RequestMapping("/exam/examManage")
public class ExamManageController {
    @Autowired
    IServiceExamManage examManage;

    @Autowired
    private PaperService paperService;

    /**
     * @author: 陈玉林
     * @date: 2017/11/8 10:48
     * @description: 进入试题管理
     */
    @GetMapping("/page")
    public String intoExamManagePage(Model model) {
        if (ExamManageUtil.hasIntoExamManagePage()) {
            model.addAttribute("cognitiveLevelList", new ExamCognitiveLevel().selectAll());
            model.addAttribute("examClass", paperService.findExamClass());
            return "exam/exam-manage";
        }
        return "401";
    }

    /**
     * @Author: 陈玉林
     * @Description: 试题搜索
     * 一审能只能看见未审核 审核未通过和自己审核的一审试题
     * searchCategoty创建的试题搜索天剑保存对象ExaminationSearchCategoty
     * @Date: 2017/8/11 9:02
     */
    @PostMapping(value = "/examList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> examinationList(ExamSearchItem searchItem) {
        Map<String, Object> map = new HashMap<>(3);
        Page page = new Page(searchItem.getStart() / searchItem.getLength() + 1, searchItem.getLength());
        Page<ExamVO> examVOPage = null;
        //超级管理员
        Integer roleId = CurrentUser.INSTANCE.getUser().getRoleId();
        Role role = new Role();
        role.setId(roleId);
        role = role.selectById();
        if (role.getName().equals("admin")) {
            examVOPage = examManage.selectAdminExamPage(page, searchItem);
        } else {
            //一审权限
            if (ExamUtil.validateAuth("sx_ys")) {
                searchItem.setSX_YS(true);
            }
            if (ExamUtil.validateAuth("nk_ys")) {
                searchItem.setNK_YS(true);
            }
            if (ExamUtil.validateAuth("ek_ys")) {
                searchItem.setEK_YS(true);
            }
            if (ExamUtil.validateAuth("fk_ys")) {
                searchItem.setFK_YS(true);
            }
            if (ExamUtil.validateAuth("sk_ys")) {
                searchItem.setSK_YS(true);
            }
            if (ExamUtil.validateAuth("cz_ys")) {
                searchItem.setCZ_YS(true);
            }
            if (ExamUtil.validateAuth("ekxw_ys")) {
                searchItem.setEKXW_YS(true);
            }
            if (ExamUtil.validateAuth("crxw_ys")) {
                searchItem.setCRXW_YS(true);
            }
            if (ExamUtil.validateAuth("kghxw_ys")) {
                searchItem.setKGHXW_YS(true);
            }
            if (ExamUtil.validateAuth("eksf_ys")) {
                searchItem.setEKSF_YS(true);
            }
            if (ExamUtil.validateAuth("crsf_ys")) {
                searchItem.setCRSF_YS(true);
            }
            if (ExamUtil.validateAuth("czzd_ys")) {
                searchItem.setCZZD_YS(true);
            }
            if (ExamUtil.validateAuth("nkct_ys")) {
                searchItem.setNKCT_YS(true);
            }
            if (ExamUtil.validateAuth("skct_ys")) {
                searchItem.setSKCT_YS(true);
            }
            if (ExamUtil.validateAuth("fkct_ys")) {
                searchItem.setFKCT_YS(true);
            }
            if (ExamUtil.validateAuth("ekct_ys")) {
                searchItem.setEKCT_YS(true);
            }
            //二审权限
            if (ExamUtil.validateAuth("sx_es")) {
                searchItem.setSX_ES(true);
            }
            if (ExamUtil.validateAuth("nk_es")) {
                searchItem.setNK_ES(true);
            }
            if (ExamUtil.validateAuth("ek_es")) {
                searchItem.setEK_ES(true);
            }
            if (ExamUtil.validateAuth("fk_es")) {
                searchItem.setFK_ES(true);
            }
            if (ExamUtil.validateAuth("sk_es")) {
                searchItem.setSK_ES(true);
            }
            if (ExamUtil.validateAuth("cz_es")) {
                searchItem.setCZ_ES(true);
            }
            if (ExamUtil.validateAuth("ekxw_es")) {
                searchItem.setEKXW_ES(true);
            }
            if (ExamUtil.validateAuth("crxw_es")) {
                searchItem.setCRXW_ES(true);
            }
            if (ExamUtil.validateAuth("kghxw_es")) {
                searchItem.setKGHXW_ES(true);
            }
            if (ExamUtil.validateAuth("eksf_es")) {
                searchItem.setEKSF_ES(true);
            }
            if (ExamUtil.validateAuth("crsf_es")) {
                searchItem.setCRSF_ES(true);
            }
            if (ExamUtil.validateAuth("czzd_es")) {
                searchItem.setCZZD_ES(true);
            }
            if (ExamUtil.validateAuth("nkct_es")) {
                searchItem.setNKCT_ES(true);
            }
            if (ExamUtil.validateAuth("skct_es")) {
                searchItem.setSKCT_ES(true);
            }
            if (ExamUtil.validateAuth("fkct_es")) {
                searchItem.setFKCT_ES(true);
            }
            if (ExamUtil.validateAuth("ekct_es")) {
                searchItem.setEKCT_ES(true);
            }
            searchItem.setCurrentUserId(CurrentUser.INSTANCE.getUserId());
            examVOPage = examManage.selectExamPage(page, searchItem);
        }
        map.put("data", examVOPage.getRecords());
        map.put("iTotalRecords", examVOPage.getTotal());
        map.put("iTotalDisplayRecords", examVOPage.getTotal());
        return map;
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题详情
     */
    @GetMapping("/detail/exam/{id}")
    public ModelAndView getDetailExamAcupoint(@PathVariable("id") String id) {
        return examManage.getExamDetail(id);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/25 9:31
     * @description: 进入试题修改页面前验证权限
     */
    @ResponseBody
    @GetMapping("/update/volidateAuth/{id}")
    public Result volidateAuthBeforeIntoUpdatePage(@PathVariable("id") String id) {
        try {
            ExamManageUtil.volidateAuthIntoExamUpdatePage(id);
        } catch (ExamException e) {
            e.printStackTrace();
            return e.getResult();
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        }
        return ResultUtil.sucess();
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 进入试题修改页面
     */
    @GetMapping("/update/page/{id}")
    public ModelAndView intoUpdatePage(@PathVariable("id") String id) {
        return examManage.intoUpdatePage(id);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-问答题-腧穴
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping(value = "/update/examAcupoint")
    public Result updateExamAcupoint(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore,@RequestParam(required = false) String[] answer1,@RequestParam(required = false) Float[] answerScore1,ExamAcupoint exam, ExamAcupointCheck1 check1) {
        return examManage.updateExamAcupoint(answer,answerScore,answer1,answerScore1,exam, check1);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-穴位定位-成人穴位
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping("/update/examAcupointAdult")
    public Result updateExamAcupointAdult(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore,ExamAcupointAdult exam, ExamAcupointAdultCheck1 check1) {
        return examManage.updateExamAcupointAdult(answer,answerScore,exam, check1);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-穴位定位-儿科穴位
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping("/update/examAcupointPediatric")
    public Result updateExamAcupointAdult(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore,ExamAcupointPediatric exam, ExamAcupointPediatricCheck1 check1) {
        return examManage.updateExamAcupointPediatric(answer,answerScore,exam, check1);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-问答题-妇、伤、儿、内、触诊
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping("/update/examWendaFSENC")
    public Result updateExamWendaFSENC(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore,ExamAnswer10 exam, ExamAnswer10Check1 check1) {
        return examManage.updateExamWendaFSENC(answer,answerScore,exam, check1);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-单项手法-成人手法、儿科手法、触诊诊断
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping("/update/examSinglePloy")
    public Result updateExamSinglePloy(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore,ExamAnswer10 exam, ExamAnswer10Check1 check1) {
        return examManage.updateExamSinglePloy(answer,answerScore,exam, check1);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/7 17:04
     * @description: 试题修改-成套手法-妇科、儿科、伤科、内科
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题修改")
    @ResponseBody
    @PostMapping("/update/examCompletePloy")
    public Result updateExamCompletePloy(@RequestParam(required = false) String[] answer,@RequestParam(required = false) Float[] answerScore, ExamAnswer30 exam, ExamAnswer30Check1 check1) {
        return examManage.updateExamCompletePloy(answer,answerScore,exam, check1);
    }


    @GetMapping("/check/getCheckStatusId")
    @ResponseBody
    public Result getCheckStatusId(@RequestParam("id") String id) {
        Result result = examManage.getExamById(id);
        return result;
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/12 9:12
     * @description: 试题审核
     * 审核状态id已经在前端处理过了，直接是需要存储的数值
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题审核")
    @ResponseBody
    @GetMapping("/check")
    public Result checkExam(@RequestParam("id") String id, @RequestParam("checkStatusId") Integer checkStatusId, @RequestParam("checkRemark") String checkRemark) {
        Result result = null;
        try {
            result = examManage.checkExam(id, checkStatusId, checkRemark);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            result = new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
        return result;
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/12 9:12
     * @description: 试题撤销审核
     */
    @LogAnnotation(moduleName = "试题管理", operate = "撤销审核")
    @ResponseBody
    @GetMapping("/check/cancel")
    public Result checkExamCancel(@RequestParam("id") String id, @RequestParam("checkStatusId") Integer checkStatusId) {
        try {
            return examManage.checkExamCancel(id, checkStatusId);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        } catch (ExamException e) {
            e.printStackTrace();
            return e.getResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/12 9:12
     * @description: 试题删除
     */
    @LogAnnotation(moduleName = "试题管理", operate = "试题删除")
    @ResponseBody
    @GetMapping("/delete")
    public Result deleteExam(@RequestParam("id") String id) {
        Result result = null;
        try {
            result = examManage.deleteExam(id);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        } catch (ExamException e1) {
            e1.printStackTrace();
            result = e1.getResult();
        } catch (Exception e1) {
            e1.printStackTrace();
            result = ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
        return result;
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/25 9:31
     * @description: 验证权限
     */
    @ResponseBody
    @GetMapping("/volidateAuth/{permission}")
    public Result volidateAuth(@PathVariable("permission") String permission) {
        return ExamUtil.volidateAuthBeforeIntoPage(permission);
    }

    /**
     * @author: 陈玉林
     * @date: 2017/12/12 9:12
     * @description: 试题导出
     */
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void export(@RequestParam("checkedId") String[] checkedId, HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException, URISyntaxException {
        examManage.writeExamToWord(checkedId, request, response);
    }

    /**
     * @author: 陈玉林
     * @date: 2018/1/2 9:54
     * @description: 设置为客观化
     */
    @GetMapping("/setToObjective")
    @ResponseBody
    public Result setToObjective(@RequestParam String id) {
        try {
            return examManage.setToObjective(id);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        } catch (ExamException e) {
            e.printStackTrace();
            return e.getResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
    }

    /**
     * @author: 陈玉林
     * @date: 2018/1/2 9:54
     * @description: 取消客观化
     */
    @GetMapping("/cancelObjective")
    @ResponseBody
    public Result cancelObjective(@RequestParam String id) {
        try {
            return examManage.cancelObjective(id);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ILLEGAL_AUTHORITY, null);
        } catch (ExamException e) {
            e.printStackTrace();
            return e.getResult();
        }catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
    }
}
